package work.chenxr.security.exception;

import com.alibaba.fastjson2.JSONObject;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import work.chenxr.security.utils.HttpContextUtil;

import java.io.IOException;

/**
 * @Author Chenxr
 * @Date 2023/10/23
 * @Description 匿名用户(token不存在 、 错误)，异常处理器
 */
public class SecurityAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
        response.setContentType("application/json; charset=utf-8");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Origin", HttpContextUtil.getOrigin());

        JSONObject result = new JSONObject();
        result.put("code", 401);
        result.put("msg", "还未授权，不能访问");

        response.getWriter().print(result.toJSONString());
    }

}
